package com.gzdh.tang.modu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzdh.tang.modu.entity.MacMainpSbruan;
import com.gzdh.tang.modu.entity.MacMainpSbruanDinner;
import com.gzdh.tang.modu.mapper.MacMainpSbruanMapper;
import com.gzdh.tang.modu.service.MacMainpSbruanDinnerService;
import com.gzdh.tang.modu.service.MacMainpSbruanService;
import com.gzdh.tang.modu.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("macMainpSbruanService")
@Slf4j
public class MacMainpSbruanServiceImpl extends ServiceImpl<MacMainpSbruanMapper, MacMainpSbruan> implements MacMainpSbruanService {


    @Autowired
    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    @Autowired
    MacMainpSbruanMapper macMainpSbruanMapper;

    @Override
    public String getDeviceSign(String deviceId) {
        MacMainpSbruan macMainpSbruan = this.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        if (macMainpSbruan == null) {
            macMainpSbruan = new MacMainpSbruan();
            macMainpSbruan.setMac(deviceId);
            macMainpSbruan.setPos("0");
            this.save(macMainpSbruan);
        }
        return macMainpSbruan.getPos() + "号机";
    }

    @Override
    public String getDinnerByDeviceId(String deviceId, Date date) {
        String dinner = "";
        MacMainpSbruan macMainpSbruan = this.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            dinner = getDinner(macMainpSbruan, new Date()).trim();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        return dinner;
    }

    @Override
    public Map<String, Object> getCanteenPayConfig(Integer id) {
        return macMainpSbruanMapper.getCanteenPayConfig(id);
    }


    private String getDinner(MacMainpSbruan macMainpSbruan, Date date) throws Exception {
        String hourMin = new SimpleDateFormat("HH:mm").format(date);
        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService.list(new QueryWrapper<MacMainpSbruanDinner>().lambda()
                .eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
            if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                return goo.getDinner();
            }
        }
        throw new Exception("未找到该餐");
    }

}